﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using Kobets.Automation.Chimera.Common;
using Kobets.Automation.Chimera.Common.Contracts;
using Kobets.Automation.Chimera.Common.Models;
using Environment = Kobets.Automation.Chimera.Common.Models.Environment;

namespace Kobets.Automation.Chimera.Controller
{
    public class ControllerContract : IControllerContract
    {
        public void Restart()
        {
            ChimeraController.Restart();
        }

        public Enums.ControllerStatus GetStatus()
        {
            return ChimeraController.ControllerStatus;
        }

        public string GetName()
        {
            return CommonMethods.GetLocalhostFqdn();
        }

        public Collection<Agent> GetAssociatedAgents()
        {
            return ChimeraController.Agents;
        }

        public void RegisterAgent(Agent agent)
        {
            if (agent == null || String.IsNullOrWhiteSpace(agent.Name)) throw new ArgumentNullException("agent");
            ChimeraController.MyEventLog.WriteEntry("Register agent: " + agent.Name);
            ChimeraController.Agents.Add(agent);
        }

        public void UnregisterAgent(Agent agent)
        {
            if (agent == null) throw new ArgumentNullException("agent");
            ChimeraController.MyEventLog.WriteEntry("Unregister agent: " + agent.Name);
            ChimeraController.Agents.Remove(ChimeraController.Agents.SingleOrDefault(n => n.Name == agent.Name));
        }

        public void RefreshAgentsStatus(Agent[] agents = null)
        {
            ChimeraController.RefreshAgentsStatus(agents);
        }

        public void ExecuteWork(Recipe recipe, Environment environment)
        {
            ChimeraController.WorkloadQueue.Enqueue(new KeyValuePair<Recipe, Environment>(recipe, environment));
        }

        public void ExecuteById(Guid recipeId, Guid environmentid)
        {
            ChimeraController.ExecuteById(recipeId, environmentid);
        }

        public void StopExecution(Guid environmentid)
        {
            ChimeraController.StopExecution(environmentid);
        }
    }
}
